#include <string.h> // for memcpy
#include "core/http/http_response.h"

namespace aliyun {

HttpResponse::HttpResponse() : body_(NULL), body_length_(0), body_buffer_length_(0), status_(0) {
}

HttpResponse::~HttpResponse() {
  if(NULL != body_) {
    delete[] body_;
    body_ = NULL;
    body_length_ = 0;
    body_buffer_length_ = 0;
  }
}

const unsigned char* HttpResponse::GetBody(size_t& body_length) const {
  body_length = body_length_;
  return body_;
}
bool HttpResponse::SetBody(const unsigned char* body, size_t body_length) {
  body_length_ = 0;
  return AppendBody(body, body_length);
}

bool HttpResponse::AppendBody(const unsigned char *body, size_t body_length) {
  if(NULL == body || body_length == 0) {
    return true;
  }
  if(body_length_ + body_length > body_buffer_length_) {
    body_buffer_length_ = body_length_ + body_length;
    body_buffer_length_ = (body_buffer_length_ + 0x7ff) & 0x7ff; // aglin 2048 bytes
    unsigned char* buffer = new unsigned char[body_buffer_length_];
    if(NULL == buffer) {
      body_buffer_length_ = 0;
      return false;
    }
    if(NULL != body_) {
      if(body_length_ > 0) {
        memcpy(buffer, body_, body_length);
      }
      delete[] body_;
    }
    body_ = buffer;
  }
  memcpy(&body_[body_length_], body, body_length);
  body_length_ += body_length;
  return true;
}

int HttpResponse::GetStatus(void) const {
  return status_;
}
void HttpResponse::SetStatus(int status) {
  status_ = status;
}
bool HttpResponse::IsSuccess(void) const {
  if(200 <= status_ && status_ < 300) {
    return true;
  }
  return false;
}

} // namespace aliyun {

// end of file
